package com.kunlun.system.config.activiti;

import java.io.IOException;
import javax.sql.DataSource;
import org.activiti.spring.SpringAsyncExecutor;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.activiti.spring.boot.AbstractProcessEngineAutoConfiguration;
import org.activiti.spring.boot.ActivitiProperties;
import org.activiti.spring.boot.JpaProcessEngineAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@AutoConfigureAfter({ DataSourceAutoConfiguration.class })
@AutoConfigureBefore({ JpaProcessEngineAutoConfiguration.class })
public class ActivitiConfig {

    @Configuration
    @EnableConfigurationProperties({ ActivitiProperties.class })
    public static class ActivitiConfiguration extends AbstractProcessEngineAutoConfiguration {
        private ActivitiDatasourceProperties activitiDatasourceProperties;

        public ActivitiDatasourceProperties getActivitiDatasourceProperties() {
            return activitiDatasourceProperties;
        }

        @Autowired
        public void setActivitiDatasourceProperties(
                ActivitiDatasourceProperties activitiDatasourceProperties) {
            this.activitiDatasourceProperties = activitiDatasourceProperties;
        }

        @Bean
        @ConditionalOnMissingBean
        public SpringProcessEngineConfiguration springProcessEngineConfiguration(DataSource dataSource,
                                                                                 PlatformTransactionManager transactionManager, SpringAsyncExecutor springAsyncExecutor)
                throws IOException {
            SpringProcessEngineConfiguration config = baseSpringProcessEngineConfiguration(dataSource,
                    transactionManager, springAsyncExecutor);
            config.setDatabaseType(this.activitiDatasourceProperties.getDatabaseType());
            return config;
        }
    }
}
